package com.ingsing.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.ingsing.common.enmus.ResultCode;
import com.ingsing.common.resp.Base;
import com.ingsing.common.resp.Resp;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author: NALHOUG
 * @time: 2019/10/16 14:03
 * @explain: 登录验证拦截器
 */

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response
            , Object handler) throws Exception {
        //获取session
        HttpSession session = request.getSession();
        System.out.println("SessionId:"+session.getId());
        System.out.println(session.getAttribute(Base.ROLE_USER));
        if (null == session) {
            //未登录
            //用户响应？
            writerLoginErrorResp(response);
            return false;
        }

        //判断session是否有用户信息
        Object userObj = session.getAttribute(Base.ROLE_USER);
        if (null == userObj) {
            //未登录
            //用户响应？
            writerLoginErrorResp(response);
            return false;
        }
        return true;
    }

    private void writerLoginErrorResp(HttpServletResponse response) {
        //用户未登录
        Resp resp = new Resp();
        resp.setResultCode(ResultCode.NOT_LOGGED_IN);
        String respStr = JSON.toJSONString(resp);

        //输出错误信息到response对象
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html; charset=utf-8");
            response.getWriter().print(respStr);
        } catch (IOException e) {
            System.out.println(e);
        }
        appendCorsHeaders(response);
    }

    private void appendCorsHeaders(HttpServletResponse response) {
        response.addHeader("Access-Control-Allow-Origin", "http://nalhoug.com");
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, HEAD");
        response.addHeader("Access-Control-Allow-Headers", "Content-Type");
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response
            , Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("[Interceptor] postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response
            , Object handler, Exception ex) throws Exception {
        System.out.println("[Interceptor] afterCompletion");
    }
}